#!/usr/local/python
# -*- coding:utf-8 -*-

import os
import datetime
from flask import Flask, jsonify, request
from flask_sqlalchemy import SQLAlchemy

# 分别从 flask_wtf 和 wtforms 导入需要的模块
# Form 作为所有我们定义的 Form 的基类
# python -m pip install flask_wtf
from flask_wtf import FlaskForm as Form
from wtforms.fields import StringField
from wtforms.validators import Required, Length
from werkzeug.datastructures import MultiDict

app = Flask(__name__)
app.config.update(dict(
    # 关闭一些不必要的提示
    SQLALCHEMY_TRACK_MODIFICATIONS=False,
    # 使用 sqlite 数据库
    SQLALCHEMY_DATABASE_URI='sqlite:////tmp/messages.db'
))
# app.config['SQLALCHEMY_DATABASE_URI']=\'sqlite:///' + os.path.join(basedir, 'data.sqlite')
# app.config['SQLACHEMY_COMMIT_ON_TEARDOWN']=True

db = SQLAlchemy(app)

class Message(db.Model):
    # 在数据库中创建表时的表名称
    __tablename__ = 'message'

    id = db.Column(db.Integer, primary_key=True)
    # index创建索引，nullable表示不能为空
    name = db.Column(db.String(64), index=True, nullable=False)
    text = db.Column(db.String(1000), nullable=False)
    # 设置了default值，所以前端不需要传创建时间过来
    created_at = db.Column(db.DateTime, default=datetime.datetime.utcnow)

    def to_dict(self):
        return {
            'name': self.name,
            'text': self.text,
            'created_at': self.created_at.strftime('%Y-%m-%dT%H:%M"%SZ')}

class MessageForm(Form):
    """
    根据 Message Model 定义相应的 Form
    """
    name = StringField(validators=[Required(), Length(1, 64)])
    text = StringField(validators=[Required(), Length(1, 1000)])
    
@app.route('/')
def index():
    return '<h1>Hello World</h1>'

@app.route('/api/messages', methods=['GET'])
def get_messages():
    '''获取所有的message，按照时间倒序排列'''
    messages = Message.query.order_by('created_at desc').all()
    return jsonify([message.to_dict() for message in messages])

@app.route('/api/messages', methods=['POST'])
def create_message():
    data = request.get_json()
    msg = Message(name=data['name'], text=data['text'])
    db.session.add(msg)
    db.session.commit()
    return jsonify(ok=True)

def main():
    app.run(debug=True)

if __name__ == '__main__':
    main()